package cn.ibizlab.businesscentral.centralapi.rest;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.math.BigInteger;
import java.util.HashMap;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSONObject;
import javax.servlet.ServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanCopier;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.http.HttpStatus;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.util.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.access.prepost.PostAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import cn.ibizlab.businesscentral.centralapi.dto.*;
import cn.ibizlab.businesscentral.centralapi.mapping.*;
import cn.ibizlab.businesscentral.core.website.domain.WebSite;
import cn.ibizlab.businesscentral.core.website.service.IWebSiteService;
import cn.ibizlab.businesscentral.core.website.filter.WebSiteSearchContext;
import cn.ibizlab.businesscentral.util.annotation.VersionCheck;

@Slf4j
@Api(tags = {"站点" })
@RestController("CentralApi-website")
@RequestMapping("")
public class WebSiteResource {

    @Autowired
    public IWebSiteService websiteService;

    @Autowired
    @Lazy
    public WebSiteMapping websiteMapping;

    @PreAuthorize("hasPermission(this.websiteMapping.toDomain(#websitedto),'iBizBusinessCentral-WebSite-Create')")
    @ApiOperation(value = "新建站点", tags = {"站点" },  notes = "新建站点")
	@RequestMapping(method = RequestMethod.POST, value = "/websites")
    public ResponseEntity<WebSiteDTO> create(@RequestBody WebSiteDTO websitedto) {
        WebSite domain = websiteMapping.toDomain(websitedto);
		websiteService.create(domain);
        WebSiteDTO dto = websiteMapping.toDto(domain);
		return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.websiteMapping.toDomain(#websitedtos),'iBizBusinessCentral-WebSite-Create')")
    @ApiOperation(value = "批量新建站点", tags = {"站点" },  notes = "批量新建站点")
	@RequestMapping(method = RequestMethod.POST, value = "/websites/batch")
    public ResponseEntity<Boolean> createBatch(@RequestBody List<WebSiteDTO> websitedtos) {
        websiteService.createBatch(websiteMapping.toDomain(websitedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @VersionCheck(entity = "website" , versionfield = "updatedate")
    @PreAuthorize("hasPermission(this.websiteService.get(#website_id),'iBizBusinessCentral-WebSite-Update')")
    @ApiOperation(value = "更新站点", tags = {"站点" },  notes = "更新站点")
	@RequestMapping(method = RequestMethod.PUT, value = "/websites/{website_id}")
    public ResponseEntity<WebSiteDTO> update(@PathVariable("website_id") String website_id, @RequestBody WebSiteDTO websitedto) {
		WebSite domain  = websiteMapping.toDomain(websitedto);
        domain .setWebsiteid(website_id);
		websiteService.update(domain );
		WebSiteDTO dto = websiteMapping.toDto(domain );
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @PreAuthorize("hasPermission(this.websiteService.getWebsiteByEntities(this.websiteMapping.toDomain(#websitedtos)),'iBizBusinessCentral-WebSite-Update')")
    @ApiOperation(value = "批量更新站点", tags = {"站点" },  notes = "批量更新站点")
	@RequestMapping(method = RequestMethod.PUT, value = "/websites/batch")
    public ResponseEntity<Boolean> updateBatch(@RequestBody List<WebSiteDTO> websitedtos) {
        websiteService.updateBatch(websiteMapping.toDomain(websitedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasPermission(this.websiteService.get(#website_id),'iBizBusinessCentral-WebSite-Remove')")
    @ApiOperation(value = "删除站点", tags = {"站点" },  notes = "删除站点")
	@RequestMapping(method = RequestMethod.DELETE, value = "/websites/{website_id}")
    public ResponseEntity<Boolean> remove(@PathVariable("website_id") String website_id) {
         return ResponseEntity.status(HttpStatus.OK).body(websiteService.remove(website_id));
    }

    @PreAuthorize("hasPermission(this.websiteService.getWebsiteByIds(#ids),'iBizBusinessCentral-WebSite-Remove')")
    @ApiOperation(value = "批量删除站点", tags = {"站点" },  notes = "批量删除站点")
	@RequestMapping(method = RequestMethod.DELETE, value = "/websites/batch")
    public ResponseEntity<Boolean> removeBatch(@RequestBody List<String> ids) {
        websiteService.removeBatch(ids);
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PostAuthorize("hasPermission(this.websiteMapping.toDomain(returnObject.body),'iBizBusinessCentral-WebSite-Get')")
    @ApiOperation(value = "获取站点", tags = {"站点" },  notes = "获取站点")
	@RequestMapping(method = RequestMethod.GET, value = "/websites/{website_id}")
    public ResponseEntity<WebSiteDTO> get(@PathVariable("website_id") String website_id) {
        WebSite domain = websiteService.get(website_id);
        WebSiteDTO dto = websiteMapping.toDto(domain);
        return ResponseEntity.status(HttpStatus.OK).body(dto);
    }

    @ApiOperation(value = "获取站点草稿", tags = {"站点" },  notes = "获取站点草稿")
	@RequestMapping(method = RequestMethod.GET, value = "/websites/getdraft")
    public ResponseEntity<WebSiteDTO> getDraft() {
        return ResponseEntity.status(HttpStatus.OK).body(websiteMapping.toDto(websiteService.getDraft(new WebSite())));
    }

    @ApiOperation(value = "检查站点", tags = {"站点" },  notes = "检查站点")
	@RequestMapping(method = RequestMethod.POST, value = "/websites/checkkey")
    public ResponseEntity<Boolean> checkKey(@RequestBody WebSiteDTO websitedto) {
        return  ResponseEntity.status(HttpStatus.OK).body(websiteService.checkKey(websiteMapping.toDomain(websitedto)));
    }

    @PreAuthorize("hasPermission(this.websiteMapping.toDomain(#websitedto),'iBizBusinessCentral-WebSite-Save')")
    @ApiOperation(value = "保存站点", tags = {"站点" },  notes = "保存站点")
	@RequestMapping(method = RequestMethod.POST, value = "/websites/save")
    public ResponseEntity<Boolean> save(@RequestBody WebSiteDTO websitedto) {
        return ResponseEntity.status(HttpStatus.OK).body(websiteService.save(websiteMapping.toDomain(websitedto)));
    }

    @PreAuthorize("hasPermission(this.websiteMapping.toDomain(#websitedtos),'iBizBusinessCentral-WebSite-Save')")
    @ApiOperation(value = "批量保存站点", tags = {"站点" },  notes = "批量保存站点")
	@RequestMapping(method = RequestMethod.POST, value = "/websites/savebatch")
    public ResponseEntity<Boolean> saveBatch(@RequestBody List<WebSiteDTO> websitedtos) {
        websiteService.saveBatch(websiteMapping.toDomain(websitedtos));
        return  ResponseEntity.status(HttpStatus.OK).body(true);
    }

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-WebSite-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-WebSite-Get')")
	@ApiOperation(value = "获取DEFAULT", tags = {"站点" } ,notes = "获取DEFAULT")
    @RequestMapping(method= RequestMethod.GET , value="/websites/fetchdefault")
	public ResponseEntity<List<WebSiteDTO>> fetchDefault(WebSiteSearchContext context) {
        Page<WebSite> domains = websiteService.searchDefault(context) ;
        List<WebSiteDTO> list = websiteMapping.toDto(domains.getContent());
        return ResponseEntity.status(HttpStatus.OK)
                .header("x-page", String.valueOf(context.getPageable().getPageNumber()))
                .header("x-per-page", String.valueOf(context.getPageable().getPageSize()))
                .header("x-total", String.valueOf(domains.getTotalElements()))
                .body(list);
	}

    @PreAuthorize("hasAnyAuthority('ROLE_SUPERADMIN','iBizBusinessCentral-WebSite-searchDefault-all') and hasPermission(#context,'iBizBusinessCentral-WebSite-Get')")
	@ApiOperation(value = "查询DEFAULT", tags = {"站点" } ,notes = "查询DEFAULT")
    @RequestMapping(method= RequestMethod.POST , value="/websites/searchdefault")
	public ResponseEntity<Page<WebSiteDTO>> searchDefault(@RequestBody WebSiteSearchContext context) {
        Page<WebSite> domains = websiteService.searchDefault(context) ;
	    return ResponseEntity.status(HttpStatus.OK)
                .body(new PageImpl(websiteMapping.toDto(domains.getContent()), context.getPageable(), domains.getTotalElements()));
	}
}

